import React from "react";
import style from "./index.module.scss";

import header from "../../base/Header/index";

import {Map, Marker, Markers, MouseTool, InfoWindow} from "react-amap";
import "./mapstylefix.scss";
/* MouseTool
    需要在地图上启用鼠标工具插件时使用；
    启用该插件可以进行鼠标画标记点、线、多边形、矩形、圆、距离量测、面积量测、拉框放大、拉框缩小等功能。
*/ 

const randomPosition = () => ({
    longitude: 116.406 + Math.random() * 3,
    latitude: 39.910 + Math.random() * 3,
});

const layerStyle = {
    padding: '5px 10px',
    fontSize:"12px",
    borderRadius:"5px",
    background: 'rgba(0,0,0,.5)',
    color:"#fff",
    border: '1px solid #ddd',
    position: 'absolute',
    top: '5px',
    left: '5px'
}

class NearbyOnsell extends React.Component{
    constructor(props){
        super(props);
        this.props=props;
        const self =this;

        this.state = {
          what: '移动地图时重新搜索',
          markPosition:[],
          // InfoWindow
          visible: true,
          value: 1,
          position: {
            longitude: 116.406,
            latitude: 39.910
          },
          offset: [0, 0],
          size: {
            width: 100,
            height: 130,
          },
          mapCenter:{
            longitude: 116.406, 
            latitude: 39.910,
          },
          markers:{
            longitude:118,
            latitude:40
          },
          clickable:false,
          zooms:[12,19],
        };
        this.toolEvents = {
            created: (tool) => {
              console.log(tool)
              self.tool = tool;
            },
            draw({obj}) {
              self.drawWhat(obj);
            }
        };
        this.mapPlugins = ['ToolBar'];
        // 116.487585177952,39.991754014757;116.487585177952,39.991653917101
        this.amapEvents = {
            created: (mapInstance) => {
              console.log('高德地图 Map 实例创建成功；如果你要亲自对实例进行操作，可以从这里开始。比如：');
              console.log(mapInstance.getZoom());
            },
        };
        this.markerEvents = {
            created: (markerInstance) => {
              console.log('高德地图 Marker 实例创建成功；如果你要亲自对实例进行操作，可以从这里开始。比如：');

              console.log(markerInstance);
              console.log(markerInstance.getPosition());
            },
            click:(e)=>{
                // console.log("markClick",e.target.w.position);
                console.log("markClick",e.target.w.extData);
                this.props.history.push({pathname:"/ww",state:{bid:e.target.w.extData.id}})
            }
        };
        this.markerPosition = { longitude: 116.406, latitude: 39.910 };
    }

    static defaultProps={
        booklist:[
            {
                name:"边城",
                cover:require("../../common/image/book-cover-default.png").default,
                position:{ 
                    longitude: 115.406,
                    latitude: 38.910
                }
            },
           {
                bid:"123123",
                name:"沉默的大多数",
                cover:require("../../common/image/1.png").default,
                position:{
                    address:"123123",
                    longitude: 116.406,
                    latitude: 39.910
                }
           },
          
        ]
    }

    drawWhat(obj) {
        let text = '';
        switch(obj.CLASS_NAME) {
          case 'AMap.Marker':
           text = `你绘制了一个标记，坐标位置是 {${obj.getPosition()}}`;
           break;
          case 'AMap.Polygon':
            text = `你绘制了一个多边形，有${obj.getPath().length}个端点`;
            break;
          case 'AMap.Circle':
            text = `你绘制了一个圆形，圆心位置为{${obj.getCenter()}}`;
            break;
          default:
            text = '';
        }
        let markPosition = obj.getPosition();
        this.setState({
          what: text,markPosition
        });
        setTimeout(()=>{
            console.log(this.state.markPosition);
        });
      }

    drawMarker(){
        if (this.tool){
          this.tool.marker();
          this.setState({
            what: '准备绘制坐标点'
          });
        }
      }

      toggleClickable() {
        this.setState({
          clickable: !this.state.clickable,
        });
      }

    selectAddress(){
        // created必须要拥有,用来初始化创建相应对象
        created: () => {
            let auto
            let placeSearch
            window.AMap.plugin('AMap.Autocomplete', () => {
                auto = new window.AMap.Autocomplete({
                    input: 'tipinput',
                    pageSize: 10,
                    pageIndex: 1,
                    citylimit: true,    // 仅搜索本城市的地名
                    city: '昆明', // 限制为只能搜索当前地区的位置
                    outPutDirAuto: true
                    // type: '汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施'
                });
            })
            // 创建搜索实例
            window.AMap.plugin('AMap.PlaceSearch', () => {
                placeSearch = new window.AMap.PlaceSearch({
                    input: 'tipinput',
                    pageSize: 10,
                    pageIndex: 1,
                    citylimit: true,    // 仅搜索本城市的地名
                });
            })

            window.AMap.event.addListener(auto, "select", (e) => {
                placeSearch.search(e.poi.name)
            })
        }
    }

    windowEvents = {
        // created: (iw) => {console.log(iw)},
        open: () => {console.log('InfoWindow opened')},
        close: () => {console.log('InfoWindow closed')},
        change: () => {console.log('InfoWindow prop changed')},
    } 

    // 改变地图中心点
    changeCenter() {
        this.setState({
          mapCenter: randomPosition()
        })
    }

    componentDidMount(){
        // console.dir("AMap-->",window.AMap)
        let {booklist} = this.props;
        // console.log(booklist)
    }

    render(){
        let bookItem = this.props.booklist.map((book,i)=>{
            let html = 
                `<div class="InfoWindow-content">
                    <div><img src=${book.cover} 
                        onclick='()=>{console.log(${book.bid})}'
                    /></div>
                    <h4>《<span>${book.name}</span>》</h4>
                </div>`;
            return (
                <InfoWindow key={i}
                    position={book.position}
                    visible={true}
                    isCustom={false}
                    content={html}
                    size={this.state.size}
                    offset={this.state.offset}
                    events={this.windowEvents}
                />
            )
        })

        return (
            <div className={style["index-root"]}>
                {header({title:"附近在售", history:this.props.history})}

                <div className={style["map-box"]}>
                    <Map plugins={this.mapPlugins} center={this.state.mapCenter} events={this.amapEvents}
                        zooms={this.state.zooms} 
                        // events={this.toolEvents}
                     >
                         <MouseTool events={this.toolEvents}/>
                         <div style={layerStyle}>{this.state.what}</div>
                            {/* {bookItem} */}

                            {/* <Marker markers={{
                                 longitude:120,
                                 latitude:40
                            }}/> */}
                            <Marker position={this.markerPosition} extData={{id:"888"}} clickable={true} events={this.markerEvents} 
                            />
                    </Map>
                </div>
                <div className={style["op-box"]} >
                    <button onClick={()=>{this.drawMarker()}}>Draw Marker</button>
                    <button onClick={() => {this.toggleClickable() }}>Clickable</button>
                    <button onClick={() => { this.changeCenter() }}>改变地图中心点</button>
                    <button onClick={() => { 
                        this.setState({ mapCenter:{
                                    longitude: 116.406, 
                                    latitude: 39.910,
                            }})}
                    }>返回中心点</button>
                </div>
            </div>
        )
    }
}

export default NearbyOnsell;